const tbody = document.querySelector("tbody");
const showModalBtn = document.querySelector(".show-modal-btn"); //模态框
const provinceDom = document.querySelector("[name=province]"); //省
const cityDom = document.querySelector("[name=city]"); //市
const countyDom = document.querySelector("[name=county]"); //县
const addForm = document.querySelector(".add-form"); //表单
const addModalLabel = document.querySelector("#addModalLabel"); //表单标题

//===================初始化
function init() {
  //获取学员信息数据
  gitSyudent();
  //初始化  省市区
  //动态获取省份
  getProvince();
  //绑定change 事件
  //绑定省份change事件
  provinceDom.addEventListener("change", function (e) {
    getCity(provinceDom.value);
  });
  //绑定市区change事件
  cityDom.addEventListener("change", function (e) {
    getCounty(provinceDom.value, cityDom.value);
  });
}
init();
//=====================渲染
async function gitSyudent() {
  const result = await axios({
    url: "/student/list",
  });
  // console.log(result);
  const list = result.data.data;
  const html = list.reduce((prve, item) => {
    const {
      id,
      name,
      sex,
      age,
      group,
      phone,
      salary,
      truesalary,
      province,
      city,
      county,
    } = item;
    return (
      prve +
      `
    <tr>
        <th scope="row">${id}</th>
        <td>${name}</td>
        <td>${age}</td>
        <td>${sex}</td>
        <td>${group}</td>
        <td>${phone}</td>
        <td>${salary}</td>
        <td>${truesalary}</td>
        <td>${province + city + county}</td>
        <td>
          <button type="button" class="btn btn-primary btn-sm " data-id=${id}>修改</button>
          <button type="button" class="btn btn-danger btn-sm" data-id=${id}>删除</button>
        </td>
      </tr>
    `
    );
  }, ""); //使用reduce 拼接 需要给一个 空字符串 ''!!!!!

  tbody.innerHTML = html;
}
gitSyudent();
//====================模态框
showModalBtn.addEventListener("click", function (e) {
  $("#addModal").modal("show");
  addModalLabel.innerText = "新增学员信息";
});
//======================省份
async function getProvince() {
  //获取省份数据
  const result = await axios({
    url: "/geo/province",
  });
  // console.log(result);
  //渲染到对相应位置
  provinceDom.innerHTML = result.data.reduce(
    (prev, item) => prev + ` <option  value="${item}">${item}</option>`,
    " <option value=''>--省--</option>"
  );
}
getProvince();
//======================市区

async function getCity(pname) {
  const result = await axios({
    url: "/geo/city",
    params: {
      pname,
    },
  });
  cityDom.innerHTML = result.data.reduce(
    (prev, item) => prev + ` <option  value="${item}">${item}</option>`,
    " <option value=''>--市--</option>"
  );
  countyDom.innerHTML = " <option value=''>--县--</option>";
}
//=======================县
async function getCounty(pname, cname) {
  const result = await axios({
    url: "/geo/county",
    params: {
      pname,
      cname,
    },
  });
  countyDom.innerHTML = result.data.reduce(
    (prev, item) => prev + ` <option value="${item}">${item}</option>`,
    " <option value=''>--县--</option>"
  );
}
//===================修改  添加
let result;
addForm.addEventListener("submit", async function (e) {
  e.preventDefault();
  //快速获取表单数据
  const data = serialize(addForm, { hash: true, empty: true });
  //判断执行的是添加还是编辑
  if ((addModalLabel.innerText = "新增学员信息")) {
    //删除id
  // 编辑那里设了id 是用来  获取要被修改的那条数据
  //但是  添加不需要id  所以 需要判断  如果点击的是添加框  则需要删除id
    delete data.id;
    result = await axios({
      url: "/student/add",
      method: "post",
      data,
    });
  } else {
    result = await axios({
      url: "/student/update",
      method: "put",
      data,
    });
  }

  //判断返回的  code 是否完全等于 0
  if (result.data.code === 0) {
    //重置表单
    addForm.reset();
    //关闭模态框
    $("#addModal").modal("hide");
    //提示添加成功
    toastr.success("操作成功");
    //重新渲染
    gitSyudent();
  }
  // console.log(data);
});
// let id;
//=====================编辑 删除
tbody.addEventListener("click", async function (e) {
  //获取id
  const id = e.target.dataset.id;
  console.log(id);
  //编辑
  if (e.target.classList.contains("btn-primary")) {
    $("#addModal").modal("show");
    addModalLabel.innerText = "修改学员信息";
    const result = await axios({
      url: "/student/one",
      params: { id },
    });
    const data = result.data.data;
    //数据回填功能  优化  填写回表单中
    //使用  遍历方式来统一实现  数据回填  不包含性别字段回填
    await getCity(data.province); //异步
    await getCounty(data.province, data.city); //异步
    const nameDom = addForm.querySelectorAll("[name]");
    nameDom.forEach((dom) => {
      if (dom.name !== "sex") {
        addForm.querySelector(`[name=${dom.name}]`).value = data[dom.name];
      }
    });
    addForm.querySelector(`[name=sex][value=${data.sex}]`).checked = true;
  }
  //删除
  if (e.target.classList.contains("btn-danger")) {
    const { id } = e.target.dataset;
    console.log(id);
    const ret = await axios({
      url: "/student/delete",
      method: "delete",
      params: {
        id,
      },
    });
    gitSyudent();
    console.log(ret);
  }
});
